package com.rzx.controller;

import com.google.gson.GsonBuilder;
import com.rzx.po.Message;
import com.rzx.po.MyFile;
import com.rzx.po.User;
import com.rzx.service.ChatService;
import com.rzx.service.LoginService;
import com.rzx.websocket.MyWebSocketHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.socket.WebSocketSession;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
@RestController
public class ChatController {

    @Autowired
    LoginService loginService;

    @Autowired
    ChatService chatService;

    @PostMapping("onlineUsers")
    @ResponseBody
    public Set<String> onlineUsers(HttpSession session) {
        Map<Long, WebSocketSession> map = MyWebSocketHandler.userSocketSessionMap;
        Set<Long> set = map.keySet();
        Iterator<Long> it = set.iterator();
        Set<String> names = new HashSet<>();
        while (it.hasNext()) {
            Long entry = it.next();
            String name = loginService.getNameById(entry);
            String user = (String) session.getAttribute("username");
            if (!user.equals(name))
                names.add(name);
        }
        return names;
    }

    // 发布系统广播（群发）
    @RequestMapping("broadcast")
    @ResponseBody
    public void broadcast(@RequestParam("uid") Long uid,
                          @RequestParam("username") String username,
                          @RequestParam("text") String text) {
        try {
            chatService.broadcast(uid, username, text);
        } catch (IOException e) {

        }
    }

    @PostMapping("getUid")
    @ResponseBody
    public User getUid(@RequestParam(value = "username", required = false) String userName) {
        Long uid = loginService.getUidByName(userName);
        User u = new User();
        u.setUid(uid);
        return u;
    }

    @RequestMapping("history")
    @ResponseBody
    public String history(@RequestParam(value = "from", required = false) Long from, @RequestParam(value = "toName", required = false) String toName) {
        Long uid = loginService.getUidByName(toName);
        List<Message> history = chatService.history(from, uid);
        return new GsonBuilder().setDateFormat("yyyy年MM月dd日 HH:mm").create().toJson(history);
    }

    @PostMapping("sendFile")
    @ResponseBody
    public String sendFile(@RequestParam("uid") Long uid,
                         @RequestParam("username") String username,
                         @RequestParam("toName") String toName,
                         @RequestParam("file") MultipartFile file) {
        if (null != uid && StringUtils.isNotBlank(toName) && StringUtils.isNotBlank(file.getOriginalFilename())) {
            Long to = loginService.getUidByName(toName);
            Message message = chatService.sendFile(uid, username, to, file);
            return new GsonBuilder().setDateFormat("yyyy年MM月dd日 HH:mm").create().toJson(message);
        }
        return "";
    }

    @RequestMapping("download")
    @ResponseBody
    public void download(@RequestParam("id") Long id, HttpServletResponse response) {
        MyFile file = chatService.getFile(id);
        if (null != file) {
            try {
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "utf-8"));
                ServletOutputStream fOut = response.getOutputStream();

                fOut.write(file.getBytes());
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
                log.error("download", e);
            }

        }
    }
}
